<?php

/**
 * This is the model class for table "mb_users".
 *
 * The followings are the available columns in table 'mb_users':
 * @property string $userId
 * @property string $userEmail
 * @property string $userName
 * @property string $userPhone
 * @property string $userPassword
 * @property string $userGroup
 * @property string $userRegDate
 * @property integer $userActive
 */
class Users extends CActiveRecord {

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'mb_users';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('userEmail, userName, userPhone, userGroup, userActive', 'required'),
			array('userImage', 'file', 'allowEmpty' => false, 'types' => 'jpg,png,bmp,jpeg', 'on' => 'create'),
			array('userImage', 'file', 'allowEmpty' => true, 'types' => 'jpg,png,bmp,jpeg', 'on' => 'update'),
			array('userPassword', 'required', 'on' => 'create'),
			array('userPassword', 'default', 'on' => 'update'),
			array('userEmail', 'email'),
			array('userEmail', 'unique'),
			array('userActive', 'numerical', 'integerOnly' => true),
			array('userEmail, userName, userPhone', 'length', 'max' => 255),
			array('userPassword', 'length', 'max' => 32),
			array('userGroup', 'length', 'max' => 5),
			array('userRegDate', 'length', 'max' => 20),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('userId, userEmail, userName, userPhone, userPassword, userGroup, userRegDate, userActive', 'safe', 'on' => 'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'userId' => 'Пользователь',
			'userEmail' => 'E-mail пользователя',
			'userName' => 'Имя пользователя',
			'userPhone' => 'Телефон пользователя',
			'userPassword' => 'Пароль пользователя',
			'userGroup' => 'Группа пользователя',
			'userImage' => 'Фото пользователя',
			'userRegDate' => 'Дата регистрации',
			'userActive' => 'А ктивность пользователя',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search() {
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('"userId"', $this->userId);
		$criteria->compare('"userEmail"', $this->userEmail, true);
		$criteria->compare('"userName"', $this->userName, true);
		$criteria->compare('"userPhone"', $this->userPhone, true);
		$criteria->compare('"userPassword"', $this->userPassword, true);
		$criteria->compare('"userGroup"', $this->userGroup, true);
		$criteria->compare('"userRegDate"', $this->userRegDate, true);
		$criteria->compare('"userActive"', $this->userActive);

		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
		));
	}

	public function beforeSave() {
		if (parent::beforeSave()) {
			if (!empty($_POST['Users']['userPassword']))
				$this->userPassword = $this->hashPassword($this->userEmail, $this->userPassword);
			$this->userRegDate = new CDbExpression('NOW()');
			if (isset($_POST['actions']))
				$this->userReject = implode(',', $_POST['actions']);

			$uploadedFile = CUploadedFile::getInstance($this, 'userImage');
			if ($uploadedFile !== NULL) {
				if (!$this->isNewRecord) {
					if (file_exists("uploads/images/users/" . $this->userImage) && !empty($this->userImage)) {
						unlink("uploads/images/users/" . $this->userImage);
					}
				}
				$newFileName = getUrl::cleanString($this->userName) . '.' . pathinfo($uploadedFile->name, PATHINFO_EXTENSION);
				copy($uploadedFile->tempName, 'uploads/images/users/' . $newFileName);
				$this->userImage = $newFileName;
			}

			return true;
		}
		return FALSE;
	}

	protected function afterDelete() {
		parent::afterDelete();
		if (file_exists("uploads/images/users/" . $this->userImage) && !empty($this->userImage))
			unlink("uploads/images/users/" . $this->userImage);
	}

	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	public static function hashPassword($userEmail, $userPassword) {
		return md5($userEmail . $userPassword);
	}

}
